var express = require('express');
var path = require('path');
// token插件
var { expressjwt } = require("express-jwt");
// var bodyParser = require("body-parser");//post1

// "使用 Express-JWT 和 Express-Unless 实现条件性路由保护", 斛决express-jwt 的 unless 方法不好用
const unless = require('express-unless');
var cors = require("cors")

//1.路由配置文件
// var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var articleRouter = require("./routes/article");//引入路由模块
var homeRouter = require("./routes/home");//引入路由模块

var app = express();
app.use(cors());

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

// app.use(cookieParser());
// 3.静态资源访问：localhost/css/style.css
app.use(express.static(path.join(__dirname, 'public')));

//post 1
// parse application/x-www-form-urlencoded
// app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
// app.use(bodyParser.json())

//post2 解析post请求
app.use(express.urlencoded({ extended: false })) //普通表单的post方式
app.use(express.json());//接收json数据
/* 

*/
// token设置
app
  .use(expressjwt({
    algorithms: ["HS256"],
    credentialsRequired: false,//关键
    secret: "blog_xpx",//加密密钥，可换,'
  })
    .unless({
      path: [
       "/login",
       "/register"
      ]
 }));


// token 解析出错时候处理（不能判断是否携带toknen）
app.use((err, req, res, next) => {
  console.log("检测token", req.header, req.auth)

  if (err.name === "UnauthorizedError") {
    return res.send({
      status: 401,
      message: "无效的token"
    });
  }
  res.send({
    status: 500,
    message: "未知的错误"
  });
})

//2.加载路由
// app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/article', articleRouter);
app.use('/home', homeRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.send({status:404,msg:"未找到路径",data:[]})
});

const port = 3000;
const server = app.listen(3000,()=>{
  var addr = server.address();
  console.log("服务启动成功~,访问地址为：http://127.0.0.1:"+ port)
})
